<template>
  <div class="container">
    <div class="breadCrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right breadCrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 列表区 -->

    <el-card class="box-card">
      <el-row :gutter="50" class="grid">
        <el-col :span="8"
          ><el-input
            v-model="input"
            @clear="clearContent"
            placeholder="请输入内容"
            clearable
          ></el-input
        ></el-col>
        <el-col :span="3"
          ><el-button
            class="searchButton"
            @click="search"
            type="primary"
            icon="el-icon-search"
            >搜索</el-button
          ></el-col
        >
        <el-col :span="3"
          ><el-button
            @click="addUserButton"
            type="primary"
            icon="el-icon-search"
            >添加用户</el-button
          ></el-col
        >
      </el-row>
      <el-table border :data="userList" style="width: 100%">
        <el-table-column type="index" label="序号" width="180">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="role_name" label="职能" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="updateState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作">
        <template v-slot="scope">
          <el-tooltip
            class="item"
            effect="dark"
            :enterable="false"
            content=" 编辑操作"
            placement="top"
          >

            <el-button
              type="success"
              @click="editUser(scope.row.id)"
              icon="el-icon-edit"
            ></el-button>

          </el-tooltip>

          <el-tooltip
            class="item"
            effect="dark"
            :enterable="false"
            content="删除操作"
            placement="top"
          >
            <el-button type="danger" @click="deleteUser(scope.row.id)" icon="el-icon-delete"></el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            :enterable="false"
            content="设置"
            placement="top"
          >
            <el-button type="warning" icon="el-icon-setting"></el-button>
          </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->

      <div class="block">
        <span class="demonstration">完整功能</span>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage4"
          :page-sizes="[100, 200, 300, 400]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="400"
        >
        </el-pagination>
      </div>
      <!-- 新增用户对话框 -->
      <el-dialog
        @close="resetForm"
        title="添加用户"
        :visible.sync="dialogVisible"
        width="50%"
      >
        <!-- 新增用户表单 -->
        <el-form
          label-position="right"
          ref="addUserFormRef"
          :rules="addUserFormRules"
          :hide-required-asterisk="false"
          label-width="80px"
          :model="addUserForm"
        >
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input show-password v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户对话框 -->
      <el-dialog
        @close="resetForm"
        title="修改用户"
        :visible.sync="editUserdialogVisible"
        width="50%"
      >
        <!-- 修改用户表单 -->
        <el-form
          label-position="right"
          ref="addUserFormRef"
          :rules="addUserFormRules"
          :hide-required-asterisk="true"
          label-width="80px"
          :model="editUserForm"
        >
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="editUserForm.username" disabled></el-input>
          </el-form-item>

          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserConfirm">确 定</el-button>
        </span>
      </el-dialog>

      卡片内容
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      dialogVisible: false,
      userList: [],
      total: '',
      queryParam: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      input: '',
      currentPage4: 0,
      addUserFormRules: {

        username: [
          {
            required: true,
            trigger: 'blur',
            message: '用户名必填'
          },
          {
            max: 10,
            min: 3,
            message: '用户名长度应该再3和10之间',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入密码'
          }
        ],
        email: [
          {
            required: true,
            trigger: 'blur',
            message: '电子邮箱地址必填'
          },
          {
            validator: this.validateEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            trigger: 'blur',
            message: '手机号码必填'
          },
          {
            max: 11,
            min: 11,
            message: '手机号码应为11位',
            trigger: 'blur'
          }
        ]
      },
      editUserForm: {},
      editUserdialogVisible: false
    }
  },
  created () {
    this.getUserList()
  },

  methods: {
    clearContent () {
      this.input = ''
    },
    async search () {
      this.queryParam.query = this.input

      const result = await this.$http.get('/users', {
        params: this.queryParam
      })
      console.log(result)
      this.userList = result.data.data.users
    },
    async updateState (user) {
      const result = await this.$http.put(
        `users/${user.id}/state/${user.mg_state}`
      )
      console.log(result)
      if (result.data.meta.status === 200) { return this.$message.success(result.data.meta.msg) }
      this.$message.error('更新失败')
      user.mg_state = !user.mg_state
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
    },
    async getUserList () {
      var res = await this.$http.get('/users', { params: this.queryParam })
      this.userList = res.data.data.users
      this.total = res.data.data.total
    },
    // 添加用户事件
    addUserButton () {
      this.dialogVisible = true
    },
    // 电子邮件地址校验
    validateEmail (rule, value, callback) {
      const reg = /[a-zA-Z]*@[a-zA-Z]*.com/

      if (reg.test(value)) return callback()
      callback(new Error('邮箱格式有误'))
    },
    // 重置表单数据
    resetForm () {
      this.$refs.addUserFormRef.resetFields()
    },
    // 添加用户后台请求
    addUser () {
      this.$refs.addUserFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('请按规定完成表单填写')
        const result = await this.$http.post('/users', this.addUserForm)
        if (!result.data.meta.status === 201) { return this.$message.error('用户添加失败') }
        const users = await this.$http.get('/users')
        this.dialogVisible = false
        this.userList = users.data.data.users
      })
    },
    // 编辑用户操作
    async editUser (id) {
      const { data: res } = await this.$http.get(`/users/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editUserForm = res.data
      this.editUserdialogVisible = true
    },
    async editUserConfirm () {
      this.$refs.addUserFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('请按规定完成表单填写')
        const { data: res } = await this.$http.put(`/users/${this.editUserForm.id}`, this.editUserForm)
        if (res.meta.status !== 200) return this.$message.error('修改操作出错')
        this.editUserdialogVisible = false
        this.getUserList()
      })
    },
    async deleteUser (id) {
      const result = await this.$MsBox.confirm('确认删除该用户吗')
      if (result !== 'confirm') return this.$message.info('取消删除操作')
      const { data: res } = await this.$http.delete(`/users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除操作出错')
      this.$message.success('删除成功')
      this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped>
.grid {
  display: flex;
  align-items: center; /*垂直居中*/
}
.searchButton {
  height: 41px;
  width: 70px;
  padding: 0 9px;
}
.breadCrumb {
  height: 51px !important;
  display: flex;
  margin-left: 10px;

  span {
    font-size: 16px;
  }
  align-items: center; /*由于flex-direction: column，因此align-items代表的是水平方向*/
}
</style>
